using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI;
using System.Data;
using EntityLayer;
using System.Collections;
using System.Web.UI.WebControls;
using InfraStructureLayer;
using BusinessLayer;
using System.Globalization;
using System.Threading;
using System.IO;

namespace WebControls
{
    public class SFPage : System.Web.UI.Page, IValidation, IClear, IReadOnly
    {

        public bool IsEditPanelOpen
        {
            get { if (ViewState["IsEditPanelOpen"] == null) { return false; } else { return Convert.ToBoolean(ViewState["IsEditPanelOpen"]); } }
            set { ViewState["IsEditPanelOpen"] = value; }
        }
        public int PageId
        {
            get
            {
                if (ViewState["PageId"] == null)
                {
                    ViewState["PageId"] = Convert.ToInt32(CurrentContext.Pages.Select("PageClassName='" + this.GetType().ToString() + "'")[0]["PageId"]);
                }
                if (Convert.ToBoolean(Convert.ToInt32(CurrentContext.Pages.Select("PageClassName='" + this.GetType().ToString() + "'")[0]["IsAdminPage"])))
                {
                    if (CurrentContext.UserId == null)
                    {
                        Response.Redirect("~/admin/login.aspx?ReturnPath=" + Request.Url.PathAndQuery);
                    }
                }
                return Convert.ToInt32(ViewState["PageId"]);
            }
        }
        private DataTable _Multilanguage;
        public DataTable Multilanguage
        {
            get
            {
                if (_Multilanguage == null)
                {
                    entMultilanguageSettings insEntMultilanguage = new entMultilanguageSettings();
                    insEntMultilanguage.PageId = this.PageId;
                    insEntMultilanguage.LanguageId = CurrentContext.LanguageId.Value;
                    this._Multilanguage = (DataTable)CurrentContext.Multilanguage[insEntMultilanguage.ToString()];
                }
                return _Multilanguage;
            }
        }

        public void LoadPages()
        {
            if (CurrentContext.Pages == null)
            {
                BusinessLayer.busPages insBusPages = new BusinessLayer.busPages();
                System.Data.DataTable insDataTablePages = insBusPages.SelectPages();

                CurrentContext.Pages = insDataTablePages;
            }

        }
        public void LoadMultilanguage()
        {
            if (CurrentContext.Multilanguage == null)
            {
                BusinessLayer.busLanguages insBusLanguages = new BusinessLayer.busLanguages();
                System.Data.DataTable insDataTableLanguages = insBusLanguages.SelectLanguages();

                Hashtable insHashTableMultiLanguage = new Hashtable();
                foreach (System.Data.DataRow dr in insDataTableLanguages.Rows)
                {
                    foreach (DataRow drPages in ((DataTable)Application["Pages"]).Rows)
                    {
                        entMultilanguageSettings insEntMultilanguageSettings = new entMultilanguageSettings();
                        insEntMultilanguageSettings.LanguageId = Convert.ToInt32(dr["LanguageId"]);
                        insEntMultilanguageSettings.PageId = Convert.ToInt32(drPages["PageId"]);
                        busMultilanguageSettings insBusMultilanguageSettings = new busMultilanguageSettings();
                        System.Data.DataTable insDataTableMultilanguageSettings = insBusMultilanguageSettings.SelectMultilanguageSettingsByLanguageIdAndPageId(insEntMultilanguageSettings);
                        insHashTableMultiLanguage.Add(insEntMultilanguageSettings.ToString(), insDataTableMultilanguageSettings);
                    }
                }
                CurrentContext.Multilanguage = insHashTableMultiLanguage;
            }
        }
        public void LoadErrorMessagesMultilanguage()
        {
            if (CurrentContext.ErrorMessagesMultilanguage == null)
            {
                busErrorMessageMultilanguageSettings insBusErrorMessageMultilanguageSettings = new busErrorMessageMultilanguageSettings();
                DataTable insDataTableErrorMessageMultilanguageSettings = insBusErrorMessageMultilanguageSettings.SelectErrorMessageMultilanguageSettings();

                Hashtable insHashTableErrorMessagesMultilanguage = new Hashtable();
                foreach (System.Data.DataRow dr in insDataTableErrorMessageMultilanguageSettings.Rows)
                {
                    insHashTableErrorMessagesMultilanguage.Add(dr["LanguageId"].ToString() + "|" + dr["ErrorMessageId"].ToString(), dr["ErrorMessageText"].ToString());
                }
                CurrentContext.ErrorMessagesMultilanguage = insHashTableErrorMessagesMultilanguage;
            }
        }
        public void LoadMenu()
        {
            if (CurrentContext.Menu == null)
            {
                BusinessLayer.busMenus insBusMenus = new BusinessLayer.busMenus();
                System.Data.DataTable insDataTableMenus = insBusMenus.SelectMenus();

                CurrentContext.Menu = insDataTableMenus;
            }
        }
        public void LoadLanguages()
        {
            if (CurrentContext.Languages == null)
            {
                BusinessLayer.busLanguages insBusLanguages = new BusinessLayer.busLanguages();
                System.Data.DataTable insDataTableLanguages = insBusLanguages.SelectLanguages();

                CurrentContext.Languages = insDataTableLanguages;
            }
        }
        public void LoadParameters()
        {
            if (CurrentContext.Parameters == null)
            {
                busParameters insBusParameters = new busParameters();
                DataTable insDataTableParameters = insBusParameters.SelectParameters();
                Hashtable insHashtableParameters = new Hashtable();
                foreach (DataRow dr in insDataTableParameters.Rows)
                {
                    insHashtableParameters.Add(dr["ParameterName"].ToString(), dr["ParameterValue"].ToString());
                }
                CurrentContext.Parameters = insHashtableParameters;
            }
        }
        public void LoadQuerystrings()
        {
            if (CurrentContext.Querystrings == null)
            {
                busQuerystrings insBusQuerystrings = new busQuerystrings();
                DataTable insDataTableQuerystrings = insBusQuerystrings.SelectQuerystrings();
                Dictionary<string, string> insQuerystrings = new Dictionary<string, string>();
                foreach (DataRow dr in insDataTableQuerystrings.Rows)
                {
                    insQuerystrings.Add(dr["Querystring"].ToString(), dr["Guid"].ToString());
                }
                CurrentContext.Querystrings = insQuerystrings;
            }
        }

        

        protected override void OnPreInit(EventArgs e)
        {

            
            LoadPages();
            LoadMultilanguage();
            LoadErrorMessagesMultilanguage();
            LoadMenu();
            LoadLanguages();
            LoadParameters();
            LoadQuerystrings();
            if (System.Web.HttpContext.Current.Items["LanguageId"] != null)
            {
                CurrentContext.LanguageId = Convert.ToInt32(System.Web.HttpContext.Current.Items["LanguageId"]);
                System.Web.HttpContext.Current.Items["LanguageId"] = null;
                //Response.Redirect(Request.Url.PathAndQuery);

            }


            if (CurrentContext.LanguageId == null)
            {
                if (Request.Cookies["Language"] != null)
                {
                    CurrentContext.LanguageId = Convert.ToInt32(Request.Cookies["Language"]["LanguageId"]);
                }
                else
                {

                    if (Request.Headers != null && Request.Headers["Accept-Language"] != null && Request.Headers["Accept-Language"].Length >= 2)
                    {
                        DataRow[] drArr = CurrentContext.Languages.Select("LanguageCulture like '%" + Request.Headers["Accept-Language"].Substring(0, 2) + "%'");
                        if (drArr.Length > 0)
                        {
                            CurrentContext.LanguageId = Convert.ToInt32(drArr[0]["LanguageId"]);
                        }
                        else
                        {
                            CurrentContext.LanguageId = Convert.ToInt32(CurrentContext.Parameters["DefaultLanguage"]);
                        }
                    }
                    else
                    {
                        CurrentContext.LanguageId = Convert.ToInt32(CurrentContext.Parameters["DefaultLanguage"]);
                    }

                }
            }
            this.Page.Title = CurrentContext.Parameters["Title"].ToString();

            this.Theme = CurrentContext.Parameters["Theme"].ToString();

            base.OnPreInit(e);
        }
        protected override void OnLoad(EventArgs e)
        {
            this.Form.Attributes.Remove("action");
            if (!Page.IsPostBack)
            {
                SetLanguage();
                if (this.Master != null)
                {
                    ((System.Web.UI.HtmlControls.HtmlGenericControl)this.Master.FindControl("mainPage")).Attributes.Add("onclick", "window.location='/" + CurrentContext.Language + "/default.aspx'");
                }
                if (!Request.Browser.Crawler)
                {
                    busReferrers insBusReferrers = new busReferrers();
                    entReferrers insEntReferrers = new entReferrers();
                    insEntReferrers.Browser = Request.Browser.Browser;
                    insEntReferrers.IpAddress = Request.UserHostAddress;
                    insEntReferrers.IsRssReferrer = false;
                    insEntReferrers.LanguageId = CurrentContext.LanguageId;
                    insEntReferrers.PageId = this.PageId;
                    if (Request.UrlReferrer != null)
                    {
                        insEntReferrers.ReferrerAddress = Request.UrlReferrer.ToString();
                    }
                    insEntReferrers.ReferrerDate = DateTime.Now;
                    insBusReferrers.InsertReferrers(insEntReferrers);
                }
                this.Id = 0;
            }

            base.OnLoad(e);
        }
        public virtual void LanguageLoad()
        {

        }
        public void SetLanguage()
        {
            SetLanguage(this);
            LanguageLoad();
        }

        public void SetLanguage(Control parControl)
        {


            for (int i = 0; i < parControl.Controls.Count; i++)
            {
                if (parControl.Controls[i] is IMultiLanguage)
                {
                    ((IMultiLanguage)parControl.Controls[i]).SetControlLanguage();

                }
                SetLanguage(parControl.Controls[i]);
            }

        }

        public void MessageBoxShow(string message)
        {

            ((Panel)this.Master.FindControl("pnlMessageBox")).Visible = true;
            ((SFLabel)this.Master.FindControl("lblErrorMessage")).Text = message + "<br>";
        }
        public void MessageBoxShow(BusinessBase business)
        {
            ((Panel)this.Master.FindControl("pnlMessageBox")).Visible = true;
            ((SFLabel)this.Master.FindControl("lblErrorMessage")).Text = business.ErrorMessage + "<br>";
            business.ErrorMessage = "";
        }
        public void MessageBoxShow(SFPage page)
        {
            ((Panel)this.Master.FindControl("pnlMessageBox")).Visible = true;
            ((SFLabel)this.Master.FindControl("lblErrorMessage")).Text = page.ErrorMessage + "<br>";

            page.ErrorMessage = "";
        }

        public new SFMasterPage Master
        {
            get { return (SFMasterPage)base.Master; }
        }
        public void OpenLanguageBox(string parNextPath)
        {
            //ScriptManager.RegisterStartupScript(this, this.GetType(), Guid.NewGuid().ToString(), "window.showModalDialog('" + this.ResolveUrl("~/Utils/Selectlanguage.aspx") + "?NextPath=" + parNextPath + "','', 'dialogWidth:700px;dialogHeight:450px;')", true);
        }

        public virtual void OpenEditPanel()
        {
            OpenEditPanelBase();
            IsEditPanelOpen = true;
        }


        public void OpenEditPanelBase()
        {
            ((Panel)this.Master.FindControl("pnlEditForm")).Visible = true;



        }

        public void CloseEditPanel()
        {
            ((Panel)this.Master.FindControl("pnlEditForm")).Visible = false;
            IsEditPanelOpen = false;
        }

        public int Id
        {
            get { if (ViewState["Id"] == null) { return 0; } else { return Convert.ToInt32(ViewState["Id"].ToString()); } }
            set { ViewState["Id"] = value; }
        }
        public string QueryStringId
        {
            get
            {
                if (ViewState["QueryStringId"] != null)
                {
                    return ViewState["QueryStringId"].ToString();
                }
                else if (System.Web.HttpContext.Current.Items["QueryStringId"] != null)
                {
                    ViewState["QueryStringId"] = System.Web.HttpContext.Current.Items["QueryStringId"];
                    return System.Web.HttpContext.Current.Items["QueryStringId"].ToString();
                }
                else
                {
                    return "";
                }
            }
            set
            {
                ViewState["QueryStringId"] = value;
            }
        }
        public string QueryStringCategory
        {
            get
            {
                if (ViewState["QueryStringCategory"] != null)
                {
                    return ViewState["QueryStringCategory"].ToString();
                }
                else if (System.Web.HttpContext.Current.Items["QueryStringCategory"] != null)
                {
                    return System.Web.HttpContext.Current.Items["QueryStringCategory"].ToString();
                }
                else
                {
                    return "";
                }
            }
            set
            {
                ViewState["QueryStringCategory"] = value;
            }
        }
        public string QueryStringArchive
        {
            get
            {
                if (ViewState["QueryStringArchive"] != null)
                {
                    return ViewState["QueryStringArchive"].ToString();
                }
                else if (System.Web.HttpContext.Current.Items["QueryStringArchive"] != null)
                {
                    return System.Web.HttpContext.Current.Items["QueryStringArchive"].ToString();
                }
                else
                {
                    return "";
                }
            }
            set
            {
                ViewState["QueryStringArchive"] = value;
            }
        }
        public string QueryStringAlbum
        {
            get
            {
                if (ViewState["QueryStringAlbum"] != null)
                {
                    return ViewState["QueryStringAlbum"].ToString();
                }
                else if (System.Web.HttpContext.Current.Items["QueryStringAlbum"] != null)
                {
                    return System.Web.HttpContext.Current.Items["QueryStringAlbum"].ToString();
                }
                else
                {
                    return "";
                }
            }
            set
            {
                ViewState["QueryStringAlbum"] = value;
            }
        }
        public string QueryStringPhoto
        {
            get
            {
                if (ViewState["QueryStringPhoto"] != null)
                {
                    return ViewState["QueryStringPhoto"].ToString();
                }
                else if (System.Web.HttpContext.Current.Items["QueryStringPhoto"] != null)
                {
                    return System.Web.HttpContext.Current.Items["QueryStringPhoto"].ToString();
                }
                else
                {
                    return "";
                }
            }
            set
            {
                ViewState["QueryStringPhoto"] = value;
            }
        }
        public virtual void Save()
        {
            if (Id != 0)
            {
                SaveExisting();
            }
            else
            {
                SaveNew();
            }
        }
        public virtual void SaveExisting()
        {
            this.CloseEditPanel();
            this.SetLanguage();
        }
        public virtual void SaveNew()
        {
            this.CloseEditPanel();
            this.SetLanguage();
        }

        #region IReadOnly Members
        public bool ReadOnly
        {
            get
            {
                if (ViewState["ReadOnly"] == null)
                {
                    return false;
                }
                return (bool)ViewState["ReadOnly"];
            }
            set
            {
                ViewState["ReadOnly"] = value;
                ReadOnlyMethod(this, value);

            }
        }
        private void ReadOnlyMethod(Control parControl, bool value)
        {
            for (int i = 0; i < parControl.Controls.Count; i++)
            {
                if (parControl.Controls[i] is IReadOnly)
                {
                    ((IReadOnly)parControl.Controls[i]).ReadOnly = value;
                }
                ReadOnlyMethod(parControl.Controls[i], value);
            }
        }
        #endregion

        #region IValidation Members

        private bool _AllowNull = false;
        public bool AllowNull
        {
            get
            {
                return _AllowNull;
            }
            set
            {
                _AllowNull = value;
            }
        }
        private bool _HasErrors;
        public bool HasErrors
        {
            get { return _HasErrors; }
        }

        private string _ErrorMessage;
        public string ErrorMessage
        {
            get
            {
                return _ErrorMessage;
            }
            set
            {
                _HasErrors = (value.Length != 0);
                _ErrorMessage = value;
            }
        }

        public new bool Validate()
        {
            bool res;
            this.ErrorMessage = "";
            res = Validate(this);
            if (res)
            {
                return !res;
            }


            return !res;
        }
        #endregion

        public bool Validate(Control parControl)
        {

            for (int i = 0; i < parControl.Controls.Count; i++)
            {
                if (!(parControl.Controls[i] is WebControls.SFUserControl))
                {
                    if (parControl.Controls[i] is IValidation)
                    {
                        ((IValidation)parControl.Controls[i]).ErrorMessage = "";
                        if (((IValidation)parControl.Controls[i]).Validate())
                        {
                            this.ErrorMessage += ((IValidation)parControl.Controls[i]).ErrorMessage;
                        }
                    }
                    else
                    {
                        Validate(parControl.Controls[i]);
                    }
                }
            }

            return this.HasErrors;
        }

        #region IClear Members

        public void Clear()
        {
            Clear(this);
        }

        #endregion
        public void Clear(Control parControl)
        {

            for (int i = 0; i < parControl.Controls.Count; i++)
            {
                if (parControl.Controls[i] is IClear)
                {
                    ((IClear)parControl.Controls[i]).Clear();
                }
                Clear(parControl.Controls[i]);
            }
        }
        protected override HtmlTextWriter CreateHtmlTextWriter(TextWriter tw)
        {
            if (Request.Browser.Crawler)
            {
                return new XhtmlTextWriter(base.CreateHtmlTextWriter(tw));
            }
            else
            {
                return base.CreateHtmlTextWriter(tw);
            }
        }
    }
}